package cn.ctyun.ipush.service.impl;


import cn.ctyun.ipush.dao.DataSourceDao;
import cn.ctyun.ipush.dao.TaskDao;
import cn.ctyun.ipush.dao.TaskDetailDao;
import cn.ctyun.ipush.model.DataSourceModel;
import cn.ctyun.ipush.model.TaskDetailModel;
import cn.ctyun.ipush.model.TaskModel;
import cn.ctyun.ipush.service.DataSourceService;
import cn.ctyun.ipush.service.ScheduleJobService;
import cn.ctyun.ipush.utils.DateUtils;
import cn.ctyun.ipush.vo.DataSourceVo;
import com.dexcoder.commons.bean.BeanConverter;
import com.dexcoder.commons.utils.UUIDUtils;
import com.dexcoder.dal.build.Criteria;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 16-6-11
 * Time: 下午5:16
 * To change this template use File | Settings | File Templates.
 */
@Service
public class DataSourceServiceImpl implements DataSourceService {

    /* 日志对象 */
    private final Logger LOG = LoggerFactory.getLogger(DataSourceServiceImpl.class);

    @Autowired
    private DataSourceDao dataSourceDao;

    @Autowired
    private TaskDao taskDao;


    @Autowired
    private TaskDetailDao taskDetailDao;

    @Autowired
    private ScheduleJobService scheduleJobService;

    /**
     * 数据源
     *
     * @param dataSourceVo
     */
    @Override
    @Transactional
    public void save(DataSourceVo dataSourceVo) {
        dataSourceVo.setDataSourceModelId(UUIDUtils.getUUID32());
        dataSourceVo.setCreateDate(DateUtils.dateToString(new Date()));
        dataSourceVo.setIsDeleted("0");
        DataSourceModel dataSourceModel = dataSourceVo.getTargetObject(DataSourceModel.class);
        //保存到数据库中
        dataSourceDao.save(dataSourceModel);
    }

    @Override
    @Transactional
    public void save(DataSourceModel dataSourceModel) {
        dataSourceModel.setDataSourceModelId(UUIDUtils.getUUID32());
        dataSourceModel.setCreateDate(DateUtils.dateToString(new Date()));
        dataSourceModel.setIsDeleted("0");
        dataSourceDao.save(dataSourceModel);
    }

    @Override
    @Transactional
    public int delete(String dataSourceId) {
        //判断是否存在引用，是否在task中.如果有引用肯定存在Job，此时不删除；
        if (taskDao.isExistDataSourceInTask(dataSourceId)) {
            return 0;
        }
        //不存在，删除缓存，数据库记录删除；无引用肯定也不存在对应的Job
        // DBUtils.deleteConnectionCache(dataSourceDao.querySingleResult(dataSourceId));
        //数据库记录软删除
        return dataSourceDao.delete(dataSourceId);
    }

    @Override
    @Transactional
    public int update(DataSourceVo dataSourceVo) {
        if (StringUtils.isEmpty(dataSourceVo.getDataSourceModelId())) {
            throw new RuntimeException("dataSource 主键ID 不存在");
        }
        //todo 额外处理
        DataSourceModel dataSourceModel = dataSourceVo.getTargetObject(DataSourceModel.class);
        DataSourceModel dataSourceModelDb = querySingleResult(dataSourceModel.getDataSourceModelId());

        if (dataSourceModel.getDataSourceName() != null)
            dataSourceModelDb.setDataSourceName(dataSourceModel.getDataSourceName());
        if (dataSourceModel.getDataSourceUrl() != null)
            dataSourceModelDb.setDataSourceUrl(dataSourceModel.getDataSourceUrl());
        if (dataSourceModel.getUserName() != null)
            dataSourceModelDb.setUserName(dataSourceModel.getUserName());
        if (dataSourceModel.getDsPassword() != null)
            dataSourceModelDb.setDsPassword(dataSourceModel.getDsPassword());
        if (dataSourceVo.getSqlListVo() != null) {
            //vo中的sqllist进行转义
            StringBuffer stringBuffer = new StringBuffer();
            for (Map.Entry<String, String> entry : dataSourceVo.getSqlListVo().entrySet()) {
                stringBuffer.append(entry.getKey()).append(":").append(entry.getValue()).append("$");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            dataSourceModelDb.setSqlListDb(stringBuffer.toString());
        }
        return dataSourceDao.update(dataSourceModelDb);
    }

    @Override
    @Transactional
    public int update(DataSourceModel dataSourceModel) {

        return dataSourceDao.update(dataSourceModel);
    }


    @Override
    public boolean isExist(DataSourceVo dataSoureVo) {
        DataSourceModel dataSourceModel = dataSoureVo.getTargetObject(DataSourceModel.class);
        if (null == dataSourceDao.querySingleResultByName(dataSourceModel.getDataSourceName())) {
            return false;
        } else {
            return true;
        }
    }


    private List<TaskDetailModel> getTaskDetailModelByDataSourceId(String dataSourceModelId) {
        List<TaskDetailModel> taskDetailModelList = new ArrayList<TaskDetailModel>();
        Criteria criteria = Criteria.select(TaskModel.class).where("dataSourceModelId", new Object[]{dataSourceModelId});
        List<TaskModel> taskModelList = taskDao.queryList(criteria);
        for (TaskModel taskModel : taskModelList) {
            TaskDetailModel taskDetailModel = taskDetailDao.querySingleResult(taskModel.getTaskDetailId());
            taskDetailModelList.add(taskDetailModel);
        }
        return taskDetailModelList;
    }

    @Override
    public DataSourceVo querySingleResultVo(String dataSourceId) {
        DataSourceModel dataSourceModel = querySingleResult(dataSourceId);
        return dataSourceModel.getTargetObject(DataSourceVo.class);
    }

    /**
     * 模糊查询列表
     *
     * @param dataSouceVo
     * @return
     */
    @Override
    public List<DataSourceVo> queryListVo(DataSourceVo dataSouceVo) {
        List<DataSourceModel> dataSourceModelList = queryList(dataSouceVo.getTargetObject(DataSourceModel.class));
        List<DataSourceVo> dataSourceVoList = BeanConverter.convert(DataSourceVo.class, dataSourceModelList);
        for (DataSourceVo dataSourceVo : dataSourceVoList) {
            if (dataSourceVo.getSqlListDb() != null) {
                String[] sqlList = dataSourceVo.getSqlListDb().split("\\$");
                Map<String, String> sqlMap = new HashMap<String, String>();
                dataSourceVo.setSqlListVo(sqlMap);
                for (String sql : sqlList) {
                    sqlMap.put(sql.split(":")[0], sql.split(":")[1]);
                }
            }
        }
        return dataSourceVoList;
    }

    /**
     * 查询全部
     *
     * @return
     */
    @Override
    public List<DataSourceVo> queryAll() {
        List<DataSourceModel> dataSourceModelList = dataSourceDao.queryAll(new DataSourceModel());
        List<DataSourceVo> dataSourceVoList = BeanConverter.convert(DataSourceVo.class, dataSourceModelList);
        for (DataSourceVo dataSourceVo : dataSourceVoList) {
            if (dataSourceVo.getSqlListDb() != null) {
                String[] sqlList = dataSourceVo.getSqlListDb().split("\\$");
                Map<String, String> sqlMap = new HashMap<String, String>();
                dataSourceVo.setSqlListVo(sqlMap);
                for (String sql : sqlList) {
                    sqlMap.put(sql.split(":")[0], sql.split(":")[1]);
                }
            }
        }
        return dataSourceVoList;
    }

    public List<DataSourceModel> queryAllModel() {
        List<DataSourceModel> dataSourceModelList = dataSourceDao.queryAll(new DataSourceModel());
        return dataSourceModelList;
    }

    /**
     * @param dataSoureVo
     * @return
     */
    @Override
    public List<DataSourceVo> queryListVoByPage(DataSourceVo dataSoureVo) {
        //分页查询
        int currentPage = dataSoureVo.getCurPage();
        int itemPages = dataSoureVo.getItemsPerPage();
        List<DataSourceModel> dataSourceModelList = dataSourceDao.queryListByPage(currentPage, itemPages, dataSoureVo);
        List<DataSourceVo> dataSourceVoList = BeanConverter.convert(DataSourceVo.class, dataSourceModelList);
        for (DataSourceVo dataSourceVo : dataSourceVoList) {
            if (dataSourceVo.getSqlListDb() != null) {
                String[] sqlList = dataSourceVo.getSqlListDb().split("\\$");
                Map<String, String> sqlMap = new HashMap<String, String>();
                dataSourceVo.setSqlListVo(sqlMap);
                for (String sql : sqlList) {
                    sqlMap.put(sql.split(":")[0], sql.split(":")[1]);
                }
            }
        }
        return dataSourceVoList;
    }

    /**
     * 精确条件查询多个
     *
     * @param dataSourceModel
     * @return
     */
    @Override
    public List<DataSourceModel> queryList(DataSourceModel dataSourceModel) {
        dataSourceModel.setIsDeleted("0");
        return dataSourceDao.queryList(dataSourceModel);
    }

    /**
     * 查询单个
     *
     * @param dataSourceId
     * @return
     */
    @Override
    public DataSourceModel querySingleResult(String dataSourceId) {
        return dataSourceDao.querySingleResult(dataSourceId);
    }


}
